﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using Net.Chirash.Twitter.TwitterClient;
using Net.Chirash.Twitter.TwitterDatabase;

namespace Net.Chirash.Twitter.TweetZone.WindowComponents
{
    /// <summary>
    /// StatusBox.xaml の相互作用ロジック
    /// </summary>
    public partial class StatusBox : UserControl
    {
        #region Constructor

        /// <summary>
        /// StatusBoxを作成します。表示するデータは引数のStatusに対応します。
        /// 引数のStatusは各種操作の対象にもなります。
        /// </summary>
        /// <param name="status">データの元、かつ操作の対象になるStatus</param>
        public StatusBox(Status status)
            : this()
        {
            DataContext = status;

            //var style = new Style(typeof(RichTextBox));
            //var setter = new EventSetter(RichTextBox.MouseLeftButtonUpEvent, new MouseButtonEventHandler((d, args) => { }));
            //setter.HandledEventsToo = true;
            //style.Setters.Add(setter);
            //this.StatusTextBox.Style = style;
        }

        public StatusBox()
        {
            InitializeComponent();

        }
        #endregion

        #region Public Types

        public delegate void DirectMessageInMainWindowCallback(string name);

        #endregion

        #region Public Properties

        public static DirectMessageInMainWindowCallback DirectMessageInMainWindow { private get; set; }

        #endregion

        #region Private Methods

        private void Reply()
        {
            UpdateForm.Visibility = Visibility.Visible;
            UpdateForm.TweetTextBox.Text = "@" + ((Status)DataContext).User.ScreenName + " ";
        }

        private void Retweet()
        {
            Reply();
            UpdateForm.TweetTextBox.Text =
                "RT " +
                UpdateForm.TweetTextBox.Text.Substring(
                    0, UpdateForm.TweetTextBox.Text.Length - 1
                ) +
                ": " + ((Status)DataContext).Text;
        }

        private void DirectMessage()
        {
            DirectMessageInMainWindow(((Status)DataContext).User.ScreenName);
        }

        private void Delete()
        {
            try
            {
                TwitterCommand command = new TwitterCommand(App.CurrentApp.Connection);
                command.Destroy((Status)DataContext);
            }
            catch (Exception ex)
            {
                //TODO:Show in TextBox
                //App.CurrentApp.ApplicationEventLog.WriteEntry(ex.ToString());
            }
        }

        private List<Inline> CreateStatusTextInlines(string text)
        {
            var list = new SortedList<int, Match>();
            //regex二種類あるので一つにまとめてIndexでソート
            foreach (var mat in regexUri.Matches(text))
            {
                list.Add((mat as Match).Index, (mat as Match));
            }
            foreach (var mat in regexUserPhrase.Matches(text))
            {
                list.Add((mat as Match).Index, (mat as Match));
            }

            var collection = new List<Inline>(list.Count);

            int beforeIndex = 0;
            foreach (var pair in list)
            {
                if (beforeIndex != pair.Value.Index)
                {
                    var run = new Run(text.Substring(beforeIndex, pair.Value.Index - beforeIndex));
                    run.Foreground = this.StatusTextBox.Foreground;
                    collection.Add(run);
                }
                if (pair.Value.Value.StartsWith("@"))
                {
                    //user
                    var userline = new Underline(new Run(text.Substring(pair.Value.Index, pair.Value.Length)));
                    userline.Foreground = this.StatusTextBox.Foreground;
                    string screenname = pair.Value.Groups[1].Value;
                    var eventfunc = new Action<object, MouseButtonEventArgs>((d, args) =>
                        {
                            System.Threading.Tasks.Task.Factory.StartNew(() =>
                            {
                                var cmd = new TwitterCommand(App.CurrentApp.Connection);
                                try
                                {
                                    var user = cmd.ShowUser(screenname);
                                    Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        var userWnd = new UserProfileWindow(user);

                                        userWnd.Show();
                                        userWnd.Activate();
                                    }), System.Windows.Threading.DispatcherPriority.Send, null);
                                }
                                catch (System.Net.WebException) { }
                            });
                        });
                    //var ulStyle = new Style(typeof(Underline));
                    //var setter = new EventSetter(Underline.MouseLeftButtonUpEvent, new MouseButtonEventHandler(eventfunc));
                    //setter.HandledEventsToo = true;

                    //ulStyle.Setters.Add(setter);
                    //userline.Style = ulStyle;
                    userline.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(eventfunc);
                    collection.Add(userline);
                }
                else
                {
                    string linktext = text.Substring(pair.Value.Index, pair.Value.Length);
                    try
                    {
                        var link = new Hyperlink(new Run(linktext));
                        link.NavigateUri = new Uri(linktext);
                        var eventfunc = new Action<object, MouseButtonEventArgs>((d, args) =>
                        {
                            System.Diagnostics.Process.Start(link.NavigateUri.ToString());
                        });
                        //var setter = new EventSetter(Hyperlink.MouseLeftButtonUpEvent, new MouseButtonEventHandler(eventfunc));
                        //var lnkStyle = new Style(typeof(Hyperlink));
                        //setter.HandledEventsToo = true;

                        //lnkStyle.Setters.Add(setter);
                        //link.Style = lnkStyle;
                        link.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(eventfunc);
                        collection.Add(link);
                    }
                    catch (UriFormatException)
                    {
                        collection.Add(new Run(linktext));
                    }
                }
                beforeIndex = pair.Value.Index + pair.Value.Length;
            }
            if (beforeIndex != text.Length - 1)
            {
                var run = new Run(text.Substring(beforeIndex));
                run.Foreground = this.StatusTextBox.Foreground;
                collection.Add(run);
            }

            return collection;
        }
        #endregion

        #region Private Events

        private void ThumbGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            StatusOperationPannel.Visibility = System.Windows.Visibility.Visible;
        }

        private void ThumbGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            StatusOperationPannel.Visibility = System.Windows.Visibility.Hidden;
        }

        private void UpdateForm_UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            UpdateForm.Visibility = Visibility.Collapsed;
        }

        void UpdateForm_UpdateCancellationPending(object sender, EventArgs e)
        {
            UpdateForm.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void ScreenNameLabel_MouseUp(object sender, MouseButtonEventArgs e)
        {
            var userWnd = new UserProfileWindow((DataContext as Status).User);
            userWnd.Show();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var status = this.DataContext as Status;
            UpdateForm.ID = status.StatusID;

            StatusOperationPannel.Reply = new MiniControls.StatusOperationPanel.OperationCallback(Reply);
            StatusOperationPannel.Retweet = new MiniControls.StatusOperationPanel.OperationCallback(Retweet);
            StatusOperationPannel.DirectMessage = new MiniControls.StatusOperationPanel.OperationCallback(DirectMessage);
            //StatusOperationPannel.User = ((Status)DataContext).User;

            UpdateForm.UpdateButton.Click += new RoutedEventHandler(UpdateForm_UpdateButton_Click);
            UpdateForm.UpdateCancellationPending += new EventHandler(UpdateForm_UpdateCancellationPending);

        }

        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.StatusTextBox != null && this.DataContext != null)
            {
                var para = new Paragraph();
                para.Inlines.AddRange(CreateStatusTextInlines((DataContext as Status).Text));
                var doc = new FlowDocument(para);
                this.StatusTextBox.Document = doc;
            }
        }

        #endregion

        #region Regex

        private static readonly Regex regexUri = new Regex(@"http[s]?://[0-9a-zA-z_\.%&\\/=\-:!;~$,\+\(\)'#\?]+", RegexOptions.Compiled);
        private static readonly Regex regexUserPhrase = new Regex(@"@([0-9a-zA-Z_]+)", RegexOptions.Compiled);

        #endregion

        #region Private ContextMenu Events

        private void ReplyMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Reply();
        }

        private void RetweetMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Retweet();
        }

        private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Delete();
        }

        #endregion
    }
}
